package com.blankii.androidlibrary.utils

import android.content.Context
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader

/**
 * author: blankii
 * created on: 2025/5/28 13:32
 * description:
 */
object FileUtil {
    /**
     * 读取asserts中的json文件，并转成string返回
     */
    fun readLargeJsonFromAssets(context: Context, fileName: String): String? {
        var reader: BufferedReader? = null
        return try {
            // 打开 assets 中的文件作为输入流
            val inputStream = context.assets.open(fileName)
            reader = BufferedReader(InputStreamReader(inputStream, Charsets.UTF_8))

            // 使用 StringBuilder 逐步构建字符串
            val stringBuilder = StringBuilder()
            var line: String?

            // 逐行读取文件内容
            while (reader.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }

            stringBuilder.toString()
        } catch (e: IOException) {
            e.printStackTrace()
            null
        } finally {
            // 确保关闭资源
            try {
                reader?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}